var async = require('async');
var superagent = require('superagent');
var cheerio = require('cheerio');

var urlObj = require('url');
var fs = require('fs');


var program = require('commander');

var http = require('http'),
    querystring = require('querystring');

var cnodeUrl = 'http://www.zhihu.com';


program
  .version('0.0.1')
  .arguments('<cmd> [env]')
  .action(function (cmd) {
     name = cmd;
  });
  
program.parse(process.argv);

if (typeof name === 'undefined') {
   console.error('no name given!');
   process.exit(1);
}

console.log('command:', name);


var trueUrl = cnodeUrl+'/people/'+name+'/answers';

var config = {
    email: "2810625476@qq.com",
    password: "Edward_sj@1989",
    _xsrf:"7a0bc2b1019a69fd8c08a21d54c22bea"
};
var contents = querystring.stringify(config);

var options = {
    host: 'www.zhihu.com', 
    path: '/login', 
    method: 'post', 
    headers: { 
        "Content-Type":"application/x-www-form-urlencoded; charset=utf8",
        "Content-Length":contents.length, 
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Encoding": "gzip,deflate,sdch",
        "Accept-Language":"zh-CN, zh;q=0.8",
        "Cache-Control":"max-age=0",
        "Connection":"Keep-Alive",  
        "Host":"www.zhihu.com",
        "Origin":"http://www.zhihu.com",
        "Referer":"http://www.zhihu.com",
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER",
        "X-Requested-With": "XMLHttpRequest",
         "Cookie":"_za=d1135c6d-4f92-406c-bc1d-1524f349c1f8; _xsrf=cb47bb5c0c1a05e78e6e75ce3520faf5; q_c1=7e98c2bc14b8400489f4add12f2e6874|1436150224000|1430309091000; _ga=GA1.2.744514158.1435026555; _gat=1; __utmt=1; __utma=51854390.744514158.1435026555.1436322672.1436331509.12; __utmb=51854390.36.9.1436331621038; __utmc=51854390; __utmz=51854390.1436262251.9.6.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/people/jiong-ni-jiang/answers; __utmv=51854390.000--|2=registration_date=20140325=1^3=entry_date=20150429=1"
        // "Cookie":"some cookie message"
    }
}; 
var cookies = null;


function login(){

    console.log('Start login....');

    var resData = '';
    // 接下来就是创建http请求
    var req=http.request(options,function(res){
        res.setEncoding("utf8"); 

        var headers = res.headers;
        
        res.on("data",function(data){
            resData += data;
        });
        // 在数据发送完毕后触发，我们只需要头就可以了  @todo 失败处理
        res.on("end", function() {
            console.log('Login success, Welcome '+ config.email);
            //把结果写入文件
            cookies  = headers["set-cookie"]; 
            cookies  = options.headers.Cookie+";"+cookies[1];
            fs.writeFileSync('cookies.dat', cookies);
            getAnswersPage();
        });
    });
    req.write(contents);
    req.end();    
    
}

fs.exists('cookies.dat',function(exists){
    
    if(exists){
        console.log('No need to login');
        cookies = fs.readFileSync('cookies.dat');
    }else{
        login();
    }
    
    getAnswersPage();   
});
    



function getAnswersPage(){
    
             console.log('Start get Answers Page....');
             
            superagent
            .get(trueUrl)
            .set('Cookie', cookies)
            .end(function(err, res){
              // get answers page first  

                if (err) {
                    return console.error(err);
                }
                getPicFromAnswers(res);

            });    
}

function getPicFromAnswers(answersPage){
    
            console.log('Start get all Answers link ....');
//            console.log('Start get pic from Answers ....');
           answersUrls = [];
            
            var $ = cheerio.load(answersPage.text);            
            var link = $('.zm-invite-pager').find('span').last().prev();
            
            var maxPage = link.find('a').html();
            
            maxPage = parseInt(maxPage);
            
            if(maxPage % 1 !== 0){
                maxPage =1;
            }
             console.log(maxPage);  
            
            var urlList = [];
            while(maxPage > 0){
                urlList.push(trueUrl+'?page='+maxPage);
                maxPage --;
            }
            
           console.log(urlList);   
             
            async.mapLimit(urlList, 5, function (url,callback) {

                superagent.get(url)
                        .set('Cookie', cookies)
                        .end(function (err, res) {

                                console.log('end:'+url);
                                 var $ = cheerio.load(res.text);   
                                $('#zh-profile-answer-list .zm-item').each(function(k,html){

                                    var href = urlObj.resolve(cnodeUrl,$(html).find('.question_link').attr('href'));

                                   answersUrls.push(href);
                               })
                               callback();
                        });                

            },function(){
                console.log('get answers Urls done....');
                console.log(answersUrls);
                
                
                fs.exists('./res/'+name+'.html',function(exists){
                    if(exists){
                        fs.unlinkSync('./res/'+name+'.html');
                    }
                    fs.appendFile('./res/'+name+'.html', '<style>img{max-width:300px;}</style>');
                });               
                async.mapLimit(answersUrls, 5, function (url,callback) {

                    superagent.get(url)
                            .set('Cookie', cookies)
                            .end(function (err, res) {
                                    console.log('geting from '+url+ '.....');
                                     var $ = cheerio.load(res.text);   
                                     
                                     var answersTitle = $('#zh-question-title').html();
                                     fs.appendFile('./res/'+name+'.html', '<br>'+answersTitle+'<br>');
                                     
                                     var answersHtml = $('#zh-question-answer-wrap').html();
                                     
                                     $(answersHtml).find('img.lazy').each(function(){
                                         var trueSrc = $(this).attr('data-original');
                                         
                                         if(trueSrc == undefined)
                                         {
                                             trueSrc = $(this).attr('data-actualsrc');
                                         }
                                         
                                         if(trueSrc != undefined)
                                         {
                                             fs.appendFile('./res/'+name+'.html', '<img src='+trueSrc+'>');
                                         }                                         
                                         
                                     });
                                     
                                     callback();
                            });                

                },function(){
                    console.log('done');
                });   

            });      
            
}
